package IO流;

import java.io.*;

public class IOTest {
    public static void main(String args[])throws IOException {
        File file = new File("E:\\从基础开始学习\\io\\test.txt");
        String testStr = "明月几时有？把酒问青天。\n" +
                "不知天上宫阙，今夕是何年。\n" +
                "我欲乘风归去，又恐琼楼玉宇，高处不胜寒。\n" +
                "起舞弄清影，何似在人间？\n" +
                "转朱阁，低绮户，照无眠。\n" +
                "不应有恨，何事长向别时圆？\n" +
                "人有悲欢离合，月有阴晴圆缺，此事古难全。\n" +
                "但愿人长久，千里共婵娟。";

//        writeBytes(file,testStr);
        writeBufferStream(file,testStr);
//        System.out.println(readBytes(file));
//        file.delete();
    }

    /**
     * 字节流的方式效率较低，不建议使用
     * @param file 输出的文件
     * @param outStr 需要写入的数据
     * @throws IOException
     */
    public static void writeBytes(File file,String outStr) throws IOException{
        OutputStream os = new FileOutputStream(file,true);
        os.write(outStr.getBytes());
        os.close();
    }

    public static String readBytes(File file)throws IOException{
        InputStream is = new FileInputStream(file);

        byte[] bytes = new byte[1024];
        StringBuilder sb = new StringBuilder();

        int length = 0;
        while ((length = is.read(bytes)) != -1){
            sb.append(new String(bytes,0,length));
        }
        is.close();
        return sb.toString();
    }

    public static void writeBufferStream(File file,String outStr)throws IOException{
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file,true));

        bos.write(outStr.getBytes());
        bos.close();
    }

}
